<?php

namespace App\Message;

use App\Ws;

class UserOnline
{
    static public $server = null;
    public $fd = null;
    public $info = [];

    public function __construct($server, $fd, $info)
    {
        self::$server = $server;
        $this->fd = $fd;
        $this->info = $info;
    }

    public function index()
    {
        $list = [];
        foreach (Ws::$table::get('uidTable') as $item) {
            if (empty($list[$item['session']])) {
                $msg = self::$server->getClientInfo($item['fd']);
                $list[$item['session']] = [
                    'from' => $item['from'],
                    'fd' => [$item['fd']],
                    'ip' => $msg['remote_ip'] . ":" . $msg['remote_port'],
                ];
                unset($msg);
            } else {
                $list[$item['session']]['fd'][] = $item['fd'];
            }
        }

        foreach (Ws::$table::get('admOnlineTable') as $adminFd) {
            self::$server->push($adminFd['fd'], json_encode(['type' => 'uid_online', 'list' => $list]));
        }

        unset($list);
    }

    public function site()
    {
        $list = [];
        foreach (Ws::$table::get('uidTable') as $item) {
            if ($item['site'] !== $this->info['site']) {
                continue;
            }
            if (empty($list[$item['session']])) {
                $msg = self::$server->getClientInfo($item['fd']);
                $list[$item['session']] = [
                    'from' => $item['from'],
                    'fd' => [$item['fd']],
                    'ip' => $msg['remote_ip'] . ":" . $msg['remote_port'],
                ];
                unset($msg);
            } else {
                $list[$item['session']]['fd'][] = $item['fd'];
            }
        }

        foreach (Ws::$table::get('admOnlineTable') as $adminFd) {
            self::$server->push($adminFd['fd'], json_encode(['type' => 'uid_online', 'list' => $list]));
        }

        unset($list);
    }

    public function ping()
    {
        //  print "ping \r\n";
    }
}
